﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using System.Web.Routing;

using ProjectBase.Core;
using ProjectBase.Core.Service;
using ProjectBase.Core.Utils;

namespace $safeprojectname$
{
    // Do you prefere Structure Map?
    // This could help you:
    // http://weblogs.asp.net/shijuvarghese/archive/2008/10/10/asp-net-mvc-tip-dependency-injection-with-structuremap.aspx
    // Attention! Think about cycled references A.B and B.A!
    // Catharis built-in solution uses lazy loading!!!

    /// <summary>
    ///     Replaces the default Factory
    /// </summary>
    public class ControllerFactory : DefaultControllerFactory
    {
        protected override Type GetControllerType(RequestContext requestContext, string controllerName)
        {
            var result = base.GetControllerType(requestContext, controllerName);
            return result;
        }
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            var routeValues = requestContext.RouteData.Values;
            if (routeValues.ContainsKey("lang"))
            {
                CultureInfo.CurrentCulture.SetCurrentCulture(routeValues["lang"].ToString());
            }

            if (controllerType.IsNull())
            {
                var ctx = requestContext.HttpContext;
                PublishingManager.Publish(this
                    , () => "no controller type passed for {0}".FormatWith(ctx.Request.ApplicationPath)
                    , Severity.Debug);

                ctx.Response.Redirect(ctx.Request.ApplicationPath);
                return null;
            }
            try
            {
                var result = Factory.CreateInstance(controllerType) as Controller;

                if (result.Is())
                {
                    PublishingManager.Publish(this
                        , () => "Controller created {0} (requested type {1})".FormatWith(result.GetType().Name, controllerType.Name)
                        , Severity.Debug);
                }
                else
                {
                    PublishingManager.Publish(this
                        , () => "Controller was not created for type {0}".FormatWith(controllerType.Name)
                        , Severity.Debug);
                }

                return result;
            }
            catch (Exception ex)
            {
                PublishingManager.Publish(this, "Controller of a type '{0}' was not created".FormatWith(controllerType.Name), ex);
                throw;
            }
        }
    }
}